﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.Service.System;
using WMS.FC.Domain.Service.Tasks.Interface;

namespace WMS.FC.Domain.Service.Tasks
{
    public class GetTaskCodeService : ServiceBase, IGetTaskCodeService
    {
        private static readonly object locker = new object();
        protected static DateTime _lastTimestamp = new DateTime();

        public GetTaskCodeService(ILogger<ServiceBase> logger, IOptions<WmsSettings> options, IMapper mapper) : base(logger, options, mapper)
        {
        }

        public async Task<ActionResult<string>> GetTaskCode()
        {
            return await Task.Run(() =>
            {
                lock (locker)
                {
                    var result = new ActionResult<string>("获取任务编码");
                    try
                    {
                        var timestamp = DateTime.Now;

                        if (timestamp < _lastTimestamp)
                        {
                            throw new Exception(string.Format("Clock moved backwards.  Refusing to generate id for {0} milliseconds", _lastTimestamp - timestamp));
                        }

                        if (_lastTimestamp == timestamp)
                        {

                            timestamp = TilNextSeconds(_lastTimestamp);
                        }

                        _lastTimestamp = timestamp;
                        result.Data = $"Task-{timestamp:yyyyMMddHHmmss}";
                    }
                    catch (Exception ex)
                    {
                        return result.Exception(ex);
                    }

                    return result;
                }
            });
        }

        protected DateTime TilNextSeconds(DateTime lastTimestamp)
        {
            var timestamp = DateTime.Now;
            while (timestamp <= lastTimestamp)
            {
                Thread.Sleep(1000);
                timestamp = DateTime.Now;
            }

            return timestamp;
        }
    }
}
